import  { getAuthorization, upload, buildFormData } from './utils.mjs'


// Token infos
const ak = 'XXXXXXXXXXXXXXXXXXX' // access key
const obsBucketName = 'xxxx'
const endpoint = 'https://xxxxxx' // Endpoint for your zone, check it on https://developer.huaweicloud.com/endpoint?OBS
const xObsAcl = 'public-read'
const contentType = 'text/plain'


// submit handler binding
const form = document.getElementById('uploadForm')
form.onsubmit = async (ev) => {
    ev.preventDefault()

    const fileElement = document.getElementsByName('file')[0]
    const filenameElement = document.getElementsByName('filename')[0]

    const file = fileElement.files[0]
    const filename = filenameElement.value

    if (!file) { return alert('File empty.') }
    if (!filename) { return alert('Filename empty.') }

    const authorizationData = await getAuthorization()

    // Build your formData
    const formData = buildFormData(file, {
        filename,
        ak,
        authorizationData,
        xObsAcl,
        contentType,
    })

    // Upload
    try {
        const result = await upload(formData, {
            obsBucketName,
            endpoint,
        })
        if (result?.status === 204) {
            alert('Upload successfully!')
            console.log('Upload successfully!', result)
        }
        else {
            alert('Upload failed!')
            console.error('Upload failed!', result)
        }
    } catch (error) {
        alert('Upload failed!')
        console.error(error)
    }
}
